package com.wgc.filter;

import com.alibaba.nacos.client.naming.utils.StringUtils;
import com.wgc.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        try{
        String path = request.getURI().getPath();
        //判断是不是登录接口
        if (path.contains("/login")) {
            return chain.filter(exchange);
        }
        //判断cookie里有没有jti
        HttpCookie token = request.getCookies().getFirst("token");
        if (token == null) {
            //jti为空，拒绝访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        String jti = token.getValue();
        //判断有没有token
        Object access_token = redisTemplate.opsForValue().get(jti);
        if (access_token == null) {
            //如果没有，拒绝访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    } catch (Exception e) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    }

    @Override
    public int getOrder() {
        return 0;
    }
}

